package com.tuo51.core.service.impl;

import com.tuo51.core.domain.org.Classes;
import com.tuo51.core.domain.org.Organization;
import com.tuo51.core.domain.org.RelClassesChildren;
import com.tuo51.core.domain.staffs.Staff;
import com.tuo51.core.repositories.ClassesChildrenRepository;
import com.tuo51.core.repositories.ClassesRepository;
import com.tuo51.core.repositories.RelClassesChildrenRepository;
import com.tuo51.core.service.ClassesService;
import com.tuo51.core.service.StaffService;
import com.tuo51.evaluate.domain.childrens.Children;
import com.tuo51.foudation.exception.BusinessException;
import com.tuo51.foudation.model.ErrorCode;
import com.tuo51.foudation.utils.annotation.OptsTrace;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;



@Service
@Slf4j
public class ClassesServiceImpl implements ClassesService {

    @Autowired
    private ClassesRepository classesRepository;

    @Autowired
    private ClassesChildrenRepository classesChildrenRepository;

    @Autowired
    private RelClassesChildrenRepository relClassesChildrenRepository;

    @Autowired
    private StaffService staffService;

    @Override
    public List<Classes> getClassesByStaff(String staffId, Boolean delete){
        Staff staff = staffService.getById(staffId);
        Organization org = staffService.staffOrgnization(staff);

        if (delete == null){
            return classesRepository.findAllByOrgId(org.getId());
        } else {
            return classesRepository.findAllByOrgIdAndDeleted(org.getId(), delete);
        }
    }

    @Override
    public Classes getClassByStaff(String staffId, String classId){
        Staff staff = staffService.getById(staffId);
        Organization org = staffService.staffOrgnization(staff);
        Classes c = classesRepository.findByOrgIdAndId(org.getId(), classId);

        if (c == null){
            throw new BusinessException(ErrorCode.CLASSES_NOT_EXIST, "班级不存在");
        }

        return c;
    }

    @Override
    public List<Children> getMemberByClassesId(String staffId, String classId) {

        Classes c = getClassByStaff(staffId, classId);


        List<Children> ret = classesChildrenRepository.findChildrenByClasses(c.getId());
        return ret;
    }

    @Override
    public boolean addMemberToClassesId(String staffId, String childrenId, String classId){

        Classes c = getClassByStaff(staffId, classId);

        String[] ids = new String[]{childrenId};

        removeChildrenClassRelation(childrenId, classId);
        addChildrenClassRelation(ids, classId);

        return true;
    }

    @Override
    public boolean addMembersToClassesId(String staffId, String[] ids, String classId){

        Classes c = getClassByStaff(staffId, classId);

        for (String childrenId : ids) {
            removeChildrenClassRelation(childrenId, classId);
        }

        addChildrenClassRelation(ids, classId);

        return true;
    }

    public boolean removeMemberToClassesId(String staffId, String childrenId, String classId){

        Classes c = getClassByStaff(staffId, classId);

        removeChildrenClassRelation(childrenId, classId);

        return true;
    }

    @OptsTrace(code = "0400")
    @Override
    @Transactional
    public Classes saveClasses(String classId, String name, String orgId, String[] childrenIds,  String remark, Integer limitNum, String targetObjectId, String inChargeTeacherId, Integer category, Integer beginMonth, Integer endMonth) {
        Classes classes = null ;

        if (StringUtils.isAllEmpty(classId, name)){
            throw new BusinessException(ErrorCode.PARAM_CAN_NOT_BLANK, "班级不存在");
        }

        if (StringUtils.isNotEmpty(classId)) {
            //修改班级
            classes = classesRepository.getOne(classId);
            if (Objects.isNull(classes)) {
                throw new BusinessException(ErrorCode.CLASSES_SAVE_ERROR, "同名字的班级已经存在");
            }
        }else {
            classes = new Classes();
            Date today = new Date();
            classes.setCreated(today);
        }

        if (StringUtils.isNotBlank(name)) { //新增班级
            Classes nameChecker = classesRepository.getByOrgIdAndName(name, orgId);
            if (Objects.nonNull(nameChecker)) {
                throw new BusinessException(ErrorCode.AREA_CLASSES_DUPLICATE, "班级名称重复");
            }
        }

        if (childrenIds != null && childrenIds.length > limitNum) {
            throw new BusinessException(ErrorCode.CLASSES_MEMBERS_MORE_THAN_LIMIT, "班级学生数超过限制");
        }

        classes.setName(name);

        classes.setOrgId(orgId);
        classes.setRemark(remark);
        classes.setLimitNum(limitNum);
        classes.setTargetObjectId(targetObjectId);

        classes.setBeginMonth(beginMonth);
        classes.setEndMonth(endMonth);
        classes.setInChargeTeacherId(inChargeTeacherId);
        classes.setInChargeTeacherName(staffService.getById(inChargeTeacherId).getRealName());

        classesRepository.save(classes);

        addChildrenClassRelation(childrenIds, classes.getId());


        return classes;
    }

    //去重复
    public  List removeDuplicate(List list) {
        HashSet h = new HashSet(list);
        list.clear();
        list.addAll(h);
        return list;
    }

    private void removeChildrenClassRelation(String childrenId,  String classId){
        relClassesChildrenRepository.deleteByChildrenIdAndAndClassesId(childrenId, classId);
    }

    private void addChildrenClassRelation(String[] childrenIds, String classId) {
        if (childrenIds == null){
            return;
        }
        List<RelClassesChildren> childrenList = new ArrayList<>();
        for (int i = 0; i < childrenIds.length; i++) {
            RelClassesChildren classesChildren = new RelClassesChildren();
            classesChildren.setChildrenId(childrenIds[i]);
            classesChildren.setClassesId(classId);
            childrenList.add(classesChildren);
        }
        relClassesChildrenRepository.saveAll(childrenList);
    }

    @Override
    public Map getDetailByClassesId(String classId) {
        Map result = new HashMap<>();
        Classes classes = classesRepository.getOne(classId);
        if (Objects.isNull(classes))
            throw new BusinessException(ErrorCode.CLASSES_NOT_EXIST, "班级不存在");

        String createClassStaffId = classes.getInChargeTeacherId();
        Staff createClassesStaff = staffService.getById(createClassStaffId);


        List<Children> childrenList = classesChildrenRepository.findChildrenByClasses(classId);

        result.put("childrenList",childrenList);

        if(createClassesStaff!=null) {
            result.put("createClassesStaff", createClassesStaff);
        }

        return result ;
    }

    @Transactional
    @Override
    public Boolean disable(String staffId, String classesId) {
        Classes classes = getClassByStaff(staffId, classesId);
        classes.setDeleted(true);

        classesRepository.save(classes);

        return true;
    }

    @Transactional
    @Override
    public Boolean enable(String staffId, String classesId) {
        Classes classes = getClassByStaff(staffId, classesId);
        classes.setDeleted(false);
        classesRepository.save(classes);
        return true;
    }
}
